package com.hht.downloadmanager.utils;

import android.content.Context;

import com.tencent.mmkv.MMKV;

public class MmkvUtils {
    private static MmkvUtils INSTALL;
    private MMKV mmkv;

    public static MmkvUtils getInstance(Context context) {
        if (INSTALL == null) {
            synchronized (MmkvUtils.class) {
                if (INSTALL == null) {
                    INSTALL = new MmkvUtils(context);
                }
            }
        }
        return INSTALL;
    }

    public MmkvUtils(Context context) {
        MMKV.initialize(context.getExternalFilesDir(null).getPath() + "/mmkv");
        mmkv = MMKV.defaultMMKV();
    }


    public void save(String key, Object object) {
        if (object instanceof String) {
            mmkv.encode(key, (String) object);
        } else if (object instanceof Integer) {
            mmkv.encode(key, (Integer) object);
        } else if (object instanceof Boolean) {
            mmkv.encode(key, (Boolean) object);
        } else if (object instanceof Float) {
            mmkv.encode(key, (Float) object);
        } else if (object instanceof Long) {
            mmkv.encode(key, (Long) object);
        }
    }

    public String getStringData(String key, Object object) {

        try {
            return mmkv.decodeString(key);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return "0";
    }

    public int getIntegerData(String key) {
        try {
            return mmkv.decodeInt(key);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public long getLongData(String key) {
        try {
            return mmkv.decodeLong(key);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void clearData(String key) {
        mmkv.removeValueForKey(key);
    }
}
